package com.lbagroup.giscovery;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;



import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import com.lbagroup.giscovery.R;
import com.lbagroup.giscovery.ShareContent.UploadDataAsyncTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.MenuItem;   
import android.view.View;   
import android.view.ContextMenu.ContextMenuInfo; 


/** 
 * Activity for loading the main Giscovery window
 * 
 * This activity is the main Giscovery activity. This activity shows with a
 * GoogleMap and search and share buttons 
 * 
 * @author XH 
 * @version 2011.1104 
 * @since 0.1 
 */
public class GiscoveryMainActivity extends MapActivity {
    
	/** 
	 * 	ID for the ABOUT menu
	 */ 
	private static final int ABOUT_ID = Menu.FIRST;
	
	/** 
	 * ID for the UPDATE menu 
	 */ 
    private static final int UPDATE_ID=Menu.FIRST+1;
    
    /** 
     * ID for the LocateMe menu 
     */ 
    private static final int LOCATEME_ID=Menu.FIRST+2;
    
    /** 
     * ID for the Settings menu 
     */ 
    private static final int SETTINGS_ID=Menu.FIRST+3;
    
   private static final String PACKAGE_NAME = "com.lbagroup.giscovery";
   
   /** 
    * The variable that holds the Latitude value in String 
    */
   private static String mStrLat=" ";
   
   /** 
    * The variable that holds the Longitude value in String 
    */
   private static String mStrLng=" ";

   /** 
    * The variable that holds the Address string 
    */
   private static String mStrAddress="  "; 
    
   /** 
    * The variable that holds the keywords put into the Search Textbox 
    */
    private static String mKeywords=" ";
    
    /** 
     * The flag that indicates if the map should always pan to the current location based on GPS signal
     * 0 - always pan to current location
 	 * 1 - do not pan to current location 
     */
    private static int mFindMeFlag; 
    
    /** 
     * This variable keeps the file location of the image file.   
     */
    private Uri imageUri;
    
  public static final String MO_PROF="ProferenceFile"; //Static variable to keep the preference file
  
  /** 
   * The variable that saves the Facebook User id
   * @deprecated facebook login is integrated...   
   */
  public static final String FB_USERID = "FBUserid";   
  
  /** 
   * This variable keeps userid retrieved from facebook   
   */
  public static String FBUserid = " ";
  
  /** 
   * This variable keeps list of facebook friends of the current user   
   */
  public static String FBFriendlist= " ";
  
  /** 
   * The variable that saves the Facebook User full name
   * @deprecated facebook login is integrated...   
   */
  public static final String FB_USERFULLNAME = "FBUserfullname";
  
  /** 
   * This variable keeps full name of the current user in Facebook   
   */
  public static String FBUserfullname = " ";
  
  /** 
   * The variable that saves the Facebook Username
   * @deprecated facebook login is integrated...   
   */
  public static final String FB_USERNAME = "FBUsername";
  
  /** 
   * This variable keeps username of the current user in Facebook   
   */
  public static String FBUsername = " ";
 
  /** 
   * The variable that saves the Facebook User password
   * @deprecated facebook login is integrated...   
   */
  public static final String FB_PASSWORD = "FBPassword";
  
  /** 
   * The variable that saves the Facebook User password
   * @deprecated facebook login is integrated...   
   */
  public static String FBPassword = " ";
  
  /** 
   * This variable keeps the number of latest updates to be received from the server in the preference file   
   */
  public static final String SET_NUMBER = "Number";
  /** 
   * This variable keeps the number of latest updates to be received from the server in the program   
   */
  public static String mSet_Number=" ";
  
  /** 
   * This variable keeps the period of latest updates to be received from the server in the preference file   
   */
  public static final String SET_PERIOD = "Period";
  
  /** 
   * This variable keeps the period of latest updates to be received from the server in the program   
   */
  public static String mSet_Period=" ";
  
  /** 
   * This variable keeps the list of key words for receiving server updates in the preference file   
   */
  public static final String SET_TAG = "Tag";
  
  /** 
   * This variable keeps the list of keywords for receiving server updates in the program   
   */
  public static String mSet_Tag=" ";
  
  /** 
   * This variable keeps the last timestamp when updates are sent from the server in the preference file   
   */
  public static final String LASTUPDATEID = "0";
  
  /** 
   * This variable keeps the update thread id of the latest update received from the server in the preference file   
   */
  public static String MAXUPDATEID="0";
  
  /** 
   * This variable keeps the number of latest update thread id received from the server in the program   
   */
  public static int LastUpdateId=0;
  
  /** 
   * The Mapview for the GoogleMap object. 
   */
    private MapView mapView;
    
    /** 
     * The MapController for the GoogleMap object 
     */ 
    private static MapController mapController;
    
    /** 
     * The location Manager object which receives location data from the GPS device
     */ 
    private LocationManager locationManager;
    
    /** 
     * The list of map overlays which includes a layer of user's current locaiton, a layer of points of interest
     * and a layer of events received from the server 
     */ 
    public static List<Overlay> mapOverlays;
    
    /** 
     * The layer that contains the user's current location 
     */ 
    public static MapOverlay itemizedoverlay; 

    /** 
     * The layer that contains the search result as points of interest 
     */ 
    public static MapOverlay resultoverlay;
    
    /** 
     * The layer that contains the updates from the server 
     */ 
    public static MapOverlay updateresultoverlay;
    
    
    /** 
     * The mark that the updates from server are received or not 
     */ 
    public static int FeedCheckedMark=0;
    
    /** 
     * This is the Facebook object which is created based on the facebook application id
     * For developers that tend to extend Giscovery, please create your own Facebook Application
     * and chagne the id at the 'new Facebook("")' part.  
     */ 
    Facebook facebook=new Facebook("185337608187267");
    
    
    /** 
     * The flat which tells if the GPS location should be used as the current location of the user 
     */ 
    public int iUseGPS=1;
    
    
    /** 
     * Method that starts automatically when the Activity is loaded. 
     * 
     * @param icicle is never used in the code 
     */ 
    @Override
    public void onCreate(Bundle icicle) {
      super.onCreate(icicle);
      setContentView(R.layout.main);
      
        mapView = (MapView) findViewById(R.id.myMap); // get the mapView object
        mapView.setBuiltInZoomControls(true);  // set the Googlemap to have zoom controls
     
        mapController = mapView.getController(); // get reference to the mapcontroller
        mapController.setZoom(14); //Set the default zoom level to be 14. Zoom 1 is world view
        
        mapOverlays = mapView.getOverlays(); //get all the overlays (layers) of the map. This will be used 
        									//to add user's location and the search results. 
        
        Drawable drawable2 = this.getResources().getDrawable(R.drawable.poi_icon); //set the icon for search results
        resultoverlay = new MapOverlay(drawable2,mapView.getContext()); // define the map layer which shows the search results

        Drawable drawable3 = this.getResources().getDrawable(R.drawable.updates_icon); // set icon for the update results
        updateresultoverlay = new MapOverlay(drawable3,mapView.getContext()); // defines the map layer which shows the update results
        
        
        Drawable drawable = this.getResources().getDrawable(R.drawable.currentlocation_icon); //set icon for the user's current location
        itemizedoverlay = new MapOverlay(drawable,mapView.getContext()); // defines the map layer which shows the user's current location
        
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //define the location manager
        // use LocationManager to ask GPS device to send updates  of GPS locations
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,  
                0, new GeoUpdateHandler());
 
         GeoPoint point = new GeoPoint(19240000,-99120000); //define a default location as the user's current locaiton
         GeoPoint point2 = new GeoPoint(0,0); // define a default location for other POIs, this location (0,0) will not be shown on the map
         OverlayItem overlayitem2 = new OverlayItem(point2, "Location2", "You are here2");
         OverlayItem overlayitem3 = new OverlayItem(point2, "Location3", "You are here3");
         mapController.animateTo(point);
         mFindMeFlag=0;
         resultoverlay.addOverlay(overlayitem2);
         mapOverlays.add(resultoverlay);
         updateresultoverlay.addOverlay(overlayitem3);
         mapOverlays.add(updateresultoverlay);
        
         OverlayItem overlayitem = new OverlayItem(point, "Location", "You are here");
       
         itemizedoverlay.addOverlay(overlayitem);
         mapOverlays.add(itemizedoverlay);
         
      findViewById(R.id.content_share).setOnClickListener(mContentShare);
      findViewById(R.id.btn_search).setOnClickListener(mSearch);
      registerForContextMenu(findViewById(R.id.btn_search));  
     
      TextView mtv=(TextView)findViewById(R.id.contentText);
      mtv.setText(mStrAddress);
      TextView maddr=(TextView)findViewById(R.id.addrText);
      maddr.setText(mStrAddress);  
      
      SharedPreferences pref1 = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
		mSet_Number  = pref1.getString(SET_NUMBER, null);
		if(mSet_Number==null)
			mSet_Number="3";
		mSet_Period = pref1.getString(SET_PERIOD, null);
		if(mSet_Period==null)
			mSet_Period="2 days";
		mSet_Tag= pref1.getString(SET_TAG, null);
		if(mSet_Tag==null)
			mSet_Tag="Copenhagen,Restaurant,Pizza";
      
     facebook.authorize(GiscoveryMainActivity.this,new String[] { "read_stream" },Facebook.FORCE_DIALOG_AUTH, new DialogListener() {
          @Override
          public void onComplete(Bundle values) {}
        
          public void onFacebookError(FacebookError error) {}

          public void onError(DialogError e) {}

          public void onCancel() {}
      });
     SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
		FBUserid = pref.getString(FB_USERID, null);
		//Toast.makeText(this, "hello"+FBUserid,Toast.LENGTH_LONG);
		if (FBUserid == null) {
     
		     try{
		 		String strProfile=facebook.request("me");
		 		
		 		try {
		 			JSONObject json = Util.parseJson(strProfile);
		 			getSharedPreferences(MO_PROF,MODE_PRIVATE)
		 	        .edit()
		 	        .putString(FB_USERFULLNAME, json.getString("name"))
		 	        .putString(FB_USERID, json.getString("id"))
		 	        .putString(FB_USERNAME, json.getString("username"))
		   	        .commit();
		 			
		 			finish();
					} catch (FacebookError e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
		 	}
		 	catch (Exception e) {
		 		
		 	}
		}
  //    facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, this);
     // facebook.authorize(GiscoveryMainActivity.this,new String[] { "read_stream" }, Facebook.FORCE_DIALOG_AUTH, GiscoveryMainActivity.this);

    }



        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
          super.onCreateOptionsMenu(menu);
          menu.add(0, ABOUT_ID, 0, R.string.about_menu);
          menu.add(0,UPDATE_ID ,0,"Update");
          menu.add(0,LOCATEME_ID ,0,"Locate Me");
          menu.add(0,SETTINGS_ID ,0,"Settings");
          return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ABOUT_ID:
              int versionCode = 0;
              String versionName = "alpha release";
              try {
                PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
                versionCode = info.versionCode;
                versionName = info.versionName;
              } catch (PackageManager.NameNotFoundException e) {
              }
              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              builder.setTitle(getString(R.string.app_name) + " " + versionName + " (" + versionCode +
                  ")");
              builder.setMessage(getString(R.string.about_message));
              builder.setPositiveButton(R.string.ok_button, null);
              builder.show();
              break;
            case UPDATE_ID:
            	startUpdate();
            	break;
            case LOCATEME_ID:
            	startLocateMe();
            	break;
            case SETTINGS_ID:
            	startSettings();
            	break;
            	
          }
          
          return super.onOptionsItemSelected(item);
        }

        public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {   
            super.onCreateContextMenu(menu, v, menuInfo);   
            if(v.getId()==R.id.btn_search){   
	            	menu.setHeaderTitle("Actions");   
	                menu.add(0, v.getId(), 0, "Locate Me");   
	                menu.add(0, v.getId(), 0, "Settings");
	            }
            }   
           
            @Override   
            public boolean onContextItemSelected(MenuItem item) {   
                if(item.getTitle()=="Locate Me"){startLocateMe();}   
                else if(item.getTitle()=="Settings"){startSettings();}   
                else {return false;}   
            return true;   
            }   
               
            /** 
             * Method that calls the LocateMe Activity 
             * 
             */ 
            public void startLocateMe(){   
                Intent intent = new Intent(); 
                intent.setClassName(GiscoveryMainActivity.this, LocateMe.class.getName());
                startActivityForResult(intent, 1110);
            }  
            
            /** 
             * Method that calls the Settings activity 
             * 
             */ 
            public void startSettings(){   
               // Toast.makeText(this, "settings function called", Toast.LENGTH_SHORT).show();
            	 Intent intent = new Intent(); 
               intent.setClassName(GiscoveryMainActivity.this, Setting.class.getName());
               startActivity(intent);
            }   
            
            /** 
             * Method that starts the Update of data by reading the input from the server
             * 
             */ 
            public void startUpdate(){   
             	 final TextView latText = (TextView) findViewById(R.id.latText);
                 final TextView lngText = (TextView) findViewById(R.id.lngText);
                 mStrLat=latText.getText().toString().trim();
                 mStrLng=lngText.getText().toString().trim();
                 if (mStrLat.trim().length()<1)
                     mStrLat="37445242";
                 if (mStrLng.trim().length()<1)
                     mStrLng="-122163427";
                 
                 double dLat=Double.parseDouble(mStrLat)/1000000;
                 double dLng=Double.parseDouble(mStrLng)/1000000;
                 int iRes=0;
                 
                 if(mStrLat.trim().length()<1||mStrLng.trim().length()<1){
                     iRes=-1;
                 }
                 else{
         			SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
         			FBUserid = pref.getString(FB_USERID, null);
         			String ss=pref.getString(LASTUPDATEID, null);
         			if (ss==null)
         				ss="0";
         			LastUpdateId= Integer.valueOf(ss);
         			MAXUPDATEID=String.valueOf(LastUpdateId);
         			if (FBUserid == null) {
         				iRes=-1;
     					Intent intent = new Intent(); 
     		            intent.setClassName(GiscoveryMainActivity.this, FBLogin.class.getName());
     		            startActivity(intent); 
         			}
         				String FBfriendlist="' '";
         				try{
         					String mrequest=facebook.request("me/friends");
         					JSONObject jObject = new JSONObject(mrequest);

         			        JSONArray results = jObject.getJSONArray("data");
         			        int a=results.length();
         			        int iresu=0;
         			        if(a>iresu){
         			        	iresu=a;
         			        }
         			        for(int i=0;i<iresu;i++){
         			                JSONObject jObj=results.getJSONObject(i);
         			                String mfrid=jObj.getString("id");
         			                FBfriendlist=FBfriendlist+",'"+mfrid+"'";
         			        }        
         				}
         				catch(Exception e){
         				
         				}
         				FBFriendlist=FBfriendlist;
         				iRes=1;
                 }
                		
         			if(iRes<0){
         				 Toast.makeText(this, "Getting your location, please wait ....", Toast.LENGTH_SHORT).show();
         				return;
         			}
         			else {
         			UpdateTask task = new UpdateTask();
 			          task.applicationContext = GiscoveryMainActivity.this;
 			          task.execute();
 		 			}
             
  }
            /** 
             * Method that calculate the number of new feeds available from the server
             * 
             */ 
            public void startUpdateNum(){   
            	 final TextView latText = (TextView) findViewById(R.id.latText);
                final TextView lngText = (TextView) findViewById(R.id.lngText);
                mStrLat=latText.getText().toString().trim();
                mStrLng=lngText.getText().toString().trim();
                if (mStrLat.trim().length()<1)
                    mStrLat="37445242";
                if (mStrLng.trim().length()<1)
                    mStrLng="-122163427";
                
                double dLat=Double.parseDouble(mStrLat)/1000000;
                double dLng=Double.parseDouble(mStrLng)/1000000;
                int iRes=0;
                
                if(mStrLat.trim().length()<1||mStrLng.trim().length()<1){
                    iRes=-1;
                }
                else{
        			SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
        			FBUserid = pref.getString(FB_USERID, null);
        			String ss=pref.getString(LASTUPDATEID, null);
        				
        				if (ss==null)
             				ss="0";
        			LastUpdateId=Integer.valueOf(ss);
        			
        			MAXUPDATEID=String.valueOf(LastUpdateId);
        			if (FBUserid == null) {
        				iRes=-1;
    					Intent intent = new Intent(); 
    		            intent.setClassName(GiscoveryMainActivity.this, FBLogin.class.getName());
    		            startActivity(intent); 
        			}
        			
        				String FBfriendlist="' '";
        				try{
        					String mrequest=facebook.request("me/friends");
        					JSONObject jObject = new JSONObject(mrequest);

        			        JSONArray results = jObject.getJSONArray("data");
        			        int a=results.length();
        			        int iresu=0;
        			        if(a>iresu){
        			        	iresu=a;
        			        }
        			        for(int i=0;i<iresu;i++){
        			                JSONObject jObj=results.getJSONObject(i);
        			                String mfrid=jObj.getString("id");
        			                FBfriendlist=FBfriendlist+",'"+mfrid+"'";
        			        }        
        				}
        				catch(Exception e){
        				
        				}
        				FBFriendlist=FBfriendlist;
        				iRes=1;
        			
              } 		
        			if(iRes<0){
        				// Toast.makeText(this, "Getting your location, please wait ....", Toast.LENGTH_SHORT).show();
        				return;
        			}
        			else {
        				
	  		          UpdateNumTask task = new UpdateNumTask();
			          task.applicationContext = GiscoveryMainActivity.this;
			          task.execute();
			        
        			}
            
 }
         
            /** 
             * Method that handles Share Button event
             * 
             */ 
        public final Button.OnClickListener mContentShare=new Button.OnClickListener() {
        public void onClick(View v){
            Intent intent = new Intent(); 
            intent.setClassName(GiscoveryMainActivity.this, ShareContent.class.getName());
            final TextView latText = (TextView) findViewById(R.id.latText);
            mStrLat=latText.getText().toString();
            final TextView lngText = (TextView) findViewById(R.id.lngText);
            mStrLng=lngText.getText().toString();
            
            intent.putExtra("lat_str",mStrLat);
            intent.putExtra("lng_str", mStrLng);
            intent.putExtra("address_str", mStrAddress);
            startActivity(intent);           
        }};
        	
        /** 
         * Method that handles the Search button event 
         * 
         */ 
        public final Button.OnClickListener mSearch=new Button.OnClickListener() {
            public void onClick(View v){
                final TextView latText = (TextView) findViewById(R.id.latText);
                final TextView lngText = (TextView) findViewById(R.id.lngText);
                mStrLat=latText.getText().toString().trim();
                mStrLng=lngText.getText().toString().trim();
//              19240000,-99120000
                if (mStrLat.trim().length()<1)
                    mStrLat="37445242";
                if (mStrLng.trim().length()<1)
                    mStrLng="-122163427";
                
                double dLat=Double.parseDouble(mStrLat)/1000000;
                double dLng=Double.parseDouble(mStrLng)/1000000;
                final TextView searchText = (TextView) findViewById(R.id.txt_search);
                mKeywords=searchText.getText().toString();
                int iRes=0;
                int iExpectedResults=10;
                
                if(mKeywords.trim().length()<1||mStrLat.trim().length()<1||mStrLng.trim().length()<1){
                    iRes=-1;
                }
                else{
        			SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
        			FBUserid = pref.getString(FB_USERID, null);
        			//Toast.makeText(this, "hello"+FBUserid,Toast.LENGTH_LONG);
        			if (FBUserid == null) {
        				iRes=-1;
    					Intent intent = new Intent(); 
    		            intent.setClassName(GiscoveryMainActivity.this, FBLogin.class.getName());
    		            startActivity(intent); 
        			}
        				String FBfriendlist="' '";
        				try{
        					String mrequest=facebook.request("me/friends");
        					JSONObject jObject = new JSONObject(mrequest);

        			        JSONArray results = jObject.getJSONArray("data");
        			        int a=results.length();
        			        int iresu=0;
        			        if(a>iresu){
        			        	iresu=a;
        			        }
        			        for(int i=0;i<iresu;i++){
        			                JSONObject jObj=results.getJSONObject(i);
        			                String mfrid=jObj.getString("id");
        			                FBfriendlist=FBfriendlist+",'"+mfrid+"'";
        			        }        
        				}
        				catch(Exception e){
        				
        				}
        				FBFriendlist=FBfriendlist;
        				iRes=1;
        			}
               
        			if(iRes<0){
        				
        				return;
        			}
        			else {
        				
	  		          SearchTask task = new SearchTask();
			          task.applicationContext = GiscoveryMainActivity.this;
			          task.execute();
        			}
                return;
        }};
        
        /** 
         * This is a standard inner class for handling GPS updates 
         * 
         */  
        public class GeoUpdateHandler implements LocationListener {

            public void onLocationChanged(Location location) {
            	if(iUseGPS<1)
            		return;
                int lat = (int) (location.getLatitude() * 1E6);
                int lng = (int) (location.getLongitude() * 1E6);
                GeoPoint point = new GeoPoint(lat, lng);
                
                final TextView latText = (TextView) findViewById(R.id.latText);
                final TextView lngText = (TextView) findViewById(R.id.lngText);
            
                  TextView maddr=(TextView)findViewById(R.id.addrText);
                 
                if (location != null) {
                    lat = (int) (location.getLatitude()* 1E6);
                    lng = (int) (location.getLongitude()* 1E6);
                    latText.setText(String.valueOf(lat));
                    lngText.setText(String.valueOf(lng));
                    
                    double dlat=location.getLatitude();
                    double dlng=location.getLongitude();
                    
                    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

                    try {
                           List<Address> addresses = geocoder.getFromLocation(dlat, dlng, 1);
                 
                          if(addresses != null) {
                               Address returnedAddress = addresses.get(0);
                               StringBuilder strReturnedAddress = new StringBuilder("");
                               for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                                   strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("  ");
                               }
                               mStrAddress=strReturnedAddress.toString();
                               maddr.setText(mStrAddress);
                          }
                          else{
                              maddr.setText("No Address returned!");
                              mStrAddress="No Address returned!";
                          }
                 } catch (IOException e) {
                     maddr.setText("Cannot get Address!");
                     mStrAddress="Cannot get Address!";
                 }
                } else {
                    latText.setText("location not available");
                    lngText.setText("location not available");
                }
                if (mFindMeFlag==0){
                    mapController.animateTo(point); //  mapController.setCenter(point);
                }
                if(itemizedoverlay.size()>0){
                    itemizedoverlay.clearall();
                }
                mStrLat=String.valueOf(lat);
                mStrLng=String.valueOf(lng);
                OverlayItem overlayitem = new OverlayItem(point, "Location", "You are at Lat: "+String.valueOf(lat)+"; Lng: "+String.valueOf(lng)+"  "+mStrAddress);
                 itemizedoverlay.addOverlay(overlayitem);
                
            }

        
            public void onProviderDisabled(String provider) {
            }

        
            public void onProviderEnabled(String provider) {
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        }
        
        /** 
         * Method that is triggered when another activity completes and send results back. 
         * 
         */ 
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        	super.onActivityResult(requestCode, resultCode, intent);
            facebook.authorizeCallback(requestCode, resultCode, intent);
            
          if (requestCode == 1110) {
            if (resultCode == RESULT_OK) {
                final TextView latText = (TextView) findViewById(R.id.latText);
                final TextView lngText = (TextView) findViewById(R.id.lngText);
                String lat=intent.getStringExtra("Latitude");
                String lng=intent.getStringExtra("Longitude");
                String add=intent.getStringExtra("Address");
                String strgps=intent.getStringExtra("GPS_FLAG");  Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                int igps=Integer.valueOf(strgps);
                if((lat.trim().length()>0)&&(lng.trim().length()>0)){
	                latText.setText(lat);
	                lngText.setText(lng);
	                
	                GeoPoint point = new GeoPoint(Integer.valueOf(lat),Integer.valueOf(lng));
	                mStrAddress=add;
	                if(itemizedoverlay.size()>0){
	                    itemizedoverlay.clearall();
	                }
	                mapController.animateTo(point);
	                OverlayItem overlayitem = new OverlayItem(point, "Location", "You are at Lat: "+lat+"; Lng: "+lng+"  "+mStrAddress);
	                 itemizedoverlay.addOverlay(overlayitem);
                }
                iUseGPS=igps;
           	
            } 
            else if (resultCode == RESULT_CANCELED) {
            }
          }
        }
        
        /** 
         * Method returns the default http client object 
         * 
         * @return a Httpclient object
         */ 
        public static DefaultHttpClient getClient() {
            DefaultHttpClient ret = null;

            //sets up parameters
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "utf-8");
            params.setBooleanParameter("http.protocol.expect-continue", false);

            //registers schemes for both http and https
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            registry.register(new Scheme("https", sslSocketFactory, 443));

            ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
            ret = new DefaultHttpClient(manager, params);
            return ret;
        }

        
        /** 
         * Method that execute the search and gets the results by calling the server
         * 
         * @param url The server url 
         * @return The result status, i.e., success 1 or failure 0
         */ 
        public int RunSearch(String url){
            int iOutput=0;
            int iResults=10;
            int firstLat=0;
            int firstLng=0;
            if(resultoverlay.size()>0){
                resultoverlay.clearall();
            }

            HttpClient httpclient = getClient();
             
            // Prepare a request object
            HttpGet httpget = new HttpGet(url);
             
            // Execute the request
            HttpResponse response;
             
            try {
            response = httpclient.execute(httpget);
             
            HttpEntity entity = response.getEntity();
             
            if (entity != null) {
             
            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            JSONObject jObject = new JSONObject(convertStreamToString(instream));

            JSONArray results = jObject.getJSONArray("results");
            
            if(results.length()<iResults){
                iResults=results.length();
            }
            for(int i=0;i<iResults;i++){
                JSONObject jObj=results.getJSONObject(i);
                JSONObject location = jObj.getJSONObject("geometry").getJSONObject("location");
                double nLat = location.getDouble("lat");
                double nLng = location.getDouble("lng");

                    
                int ilat = (int) (nLat * 1E6);
                int ilng = (int) (nLng * 1E6);
                if(i==0){
                    firstLat=ilat;
                    firstLng=ilng;
                }
                GeoPoint mypoint = new GeoPoint(ilat, ilng);
                
             String strObjName="POI";
             try{
                 strObjName=jObj.getString("name").toString();
        
             }
             catch(Exception e){
                 strObjName="POI";
             }
             
             //OverlayItem overlayitem = new OverlayItem(mypoint, "Result ["+Integer.toString(i)+"]", strObjName);
             OverlayItem overlayitem = new OverlayItem(mypoint, "Result ["+Integer.toString(i)+"]", strObjName);
             resultoverlay.addOverlay(overlayitem);
     
            }
            
            iOutput=iResults;
            //instream.close();
            }
            else{

                iResults=0;
                iOutput=1;
            }
            } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            //mapOverlays.add(resultoverlay);
            if(firstLat!=0&&firstLng!=0){
             GeoPoint pointFirst = new GeoPoint(firstLat,firstLng);
        //   OverlayItem overlayitem3 = new OverlayItem(point3, "Location3", "You are here3");
             mapController.animateTo(pointFirst);
             //resultoverlay.addOverlay(overlayitem3);
             mFindMeFlag=1;
            }
            
            return iOutput;
        }
        
        /** 
         * Method that call the web service at movingobject.org in order to get the search results. 
         * 
         * @return The result status, i.e., success 1 or failure 0
         */ 
        public static int RunMOSearch(){
        	int iRes=1;
            
            double dLat=Double.parseDouble(mStrLat)/1000000;
            double dLng=Double.parseDouble(mStrLng)/1000000;
            int iExpectedResults=10;
	
            String msearchurl="http://www.movingobject.org/facebook/searchpoi2.php";
               
            try{
            	JSONObject mJOB=new JSONObject();
                mJOB.put("fbuserid", FBUserid);
                mJOB.put("keywords", mKeywords.trim());
                mJOB.put("fbfriendlist", FBFriendlist);
                mJOB.put("latitude",mStrLat);
                mJOB.put("longitude",mStrLng);
                mJOB.put("setnumber", mSet_Number);
                mJOB.put("setperiod",mSet_Period);
                mJOB.put("settags", mSet_Tag);
               
                iRes=RunMOSearch(msearchurl,mJOB);
            }
            catch (Exception e){
            	iRes=0;
            }
        	return iRes;
        }
        
        /** 
         * Method that calls an URL and get the search results  
         * 
         * @param url The URL of the search service 
         * @param c The parameter used for the search service
         * @return The result status, i.e., success 1 or failure 0
         */ 
        private static int RunMOSearch(String url,JSONObject c){
            int iOutput=0;
            int iResults=10;
            int firstLat=0;
            int firstLng=0;
           
            
            if(resultoverlay.size()>0){
                resultoverlay.clearall();
            }
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
            // Limit
            HttpResponse response;
            String mquery=" ";
       //     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            
            try {
				HttpPost post = new HttpPost(url);


			    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			    nameValuePairs.add(new BasicNameValuePair("request", c.toString()));
 //               se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
 //               post.setEntity(se);
			    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//
                response = client.execute(post);

				if (response != null) {
				
					HttpEntity entity = response.getEntity();
					String temp = EntityUtils.toString(entity);
					JSONObject jObject = new JSONObject(temp);
	//				JSONObject jObject = new JSONObject(convertStreamToString(instream));
					JSONObject jObject1=jObject.getJSONObject("query");
					mquery=jObject1.getString("content");
		            JSONArray results=jObject.getJSONArray("data");
	            
		            if(results.length()<iResults){
		                iResults=results.length();
		            }
		            for(int i=0;i<iResults;i++){
		            	JSONObject jObj=results.getJSONObject(i);
		            //    double nLat = jObj.getDouble("latitude");
		            //    double nLng = jObj.getDouble("longitude");
	
		              int ilat=jObj.getInt("latitude");
		              int ilng=jObj.getInt("longitude");
		            //    int ilat = (int) (nLat * 1E6);
		            //    int ilng = (int) (nLng * 1E6);
		                if(i==0){
		                    firstLat=ilat;
		                    firstLng=ilng;
		                }
		                GeoPoint mypoint = new GeoPoint(ilat, ilng);
		                
			             String strObjName="POI";
			             try{
			                 strObjName=jObj.getString("comment").toString();
			        
			             }
			             catch(Exception e){
			                 strObjName="POI";
			             }
			             int myuploadid=jObj.getInt("uploadid");
			             String imgpath="http://www.movingobject.org/testfolder/lbademo/phpservice/"+jObj.getString("imagepath");
			             String name=jObj.getString("fbuserfullname");
						 String comment=jObj.getString("comment");
						 String address=jObj.getString("address");
						 String mydate=jObj.getString("uploaddate");
						 String mytitle=jObj.getString("title");
						 int myflag=jObj.getInt("shareflag");
						if(myflag==0){
								name="Someone";
							}
						String contentString="<html Content-Type: text/html; charset=utf-8> <head></head><body><p><b>" +name+"</b>  have discovered: </p>"+
					    "<p>"+comment+"</p>"+
					    "<p><img src='"+imgpath+"' width='96' height='96' /> </p>"+
					  "<p> at address: "+address+"</p>"+
					 "<p> at time: "+mydate+"</p><p> <a href='http://www.movingobject.org/facebook/showpoi.php?pid="+
					 myuploadid+"' target='_blank'>more...</a></p></body></html>";	

			             //OverlayItem overlayitem = new OverlayItem(mypoint, "Result ["+Integer.toString(i)+"]", strObjName);
			             OverlayItem overlayitem = new OverlayItem(mypoint,mytitle, contentString);
			             resultoverlay.addOverlay(overlayitem);
		     
		            }
	            
	            iOutput=iResults;
	            //instream.close();
	            }
	            else{

	                iResults=0;
	                iOutput=0;
	            }
            } 
            catch (Exception e) {
            	e.printStackTrace();
            	iOutput=0;
			}

            if(firstLat!=0&&firstLng!=0){
             GeoPoint pointFirst = new GeoPoint(firstLat,firstLng);
        //   OverlayItem overlayitem3 = new OverlayItem(point3, "Location3", "You are here3");
             mapController.animateTo(pointFirst);
             //resultoverlay.addOverlay(overlayitem3);
             mFindMeFlag=1;
            }
            
            return iOutput;
     }
        
        /** 
         * Method that calls the update of data from server 
         * 
         * @return The result, 1-success, 0-failure
         */ 
        private static int RunUpdates(){
            int iOutput=0;
            int iResults=10;
            int firstLat=0;
            int firstLng=0;
           
            double dLat=Double.parseDouble(mStrLat)/1000000;
            double dLng=Double.parseDouble(mStrLng)/1000000;
			
            String murl="http://www.movingobject.org/facebook/updatefeed.php";
            JSONObject mJOB=new JSONObject();   
            try{
            	
                mJOB.put("fbuserid", FBUserid);
                mJOB.put("keywords", mKeywords.trim());
                mJOB.put("fbfriendlist", FBFriendlist);
                mJOB.put("latitude",mStrLat);
                mJOB.put("longitude",mStrLng);
                mJOB.put("lastupdateid",LastUpdateId);
                mJOB.put("setnumber", mSet_Number);
                mJOB.put("setperiod",mSet_Period);
                mJOB.put("settags", mSet_Tag);
               }
               catch (Exception e){
            	   iOutput=0;
               }
             
            if(updateresultoverlay.size()>0){
                updateresultoverlay.clearall();
            }
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
            // Limit
            HttpResponse response;
            String mquery=" ";
            
            try {
				HttpPost post = new HttpPost(murl);
			    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			    nameValuePairs.add(new BasicNameValuePair("request", mJOB.toString()));
			    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = client.execute(post);

				
				if (response != null) {
				
				//	InputStream instream = response.getEntity().getContent(); // Get the
					HttpEntity entity = response.getEntity();
					String temp = EntityUtils.toString(entity);
					JSONObject jObject = new JSONObject(temp);
	//				JSONObject jObject = new JSONObject(convertStreamToString(instream));
					JSONObject jObject1=jObject.getJSONObject("query");
					mquery=jObject1.getString("content");
		            JSONArray results=jObject.getJSONArray("data");
		            iResults=10;
		            if(results.length()<iResults){
		                iResults=results.length();
		            }
		            int iMaxUpdateid=0;
		            for(int i=0;i<iResults;i++){
		            	JSONObject jObj=results.getJSONObject(i);
	
		              int ilat=jObj.getInt("latitude");
		              int ilng=jObj.getInt("longitude");
		              int iUID=jObj.getInt("uploadid");
		              if(iUID>iMaxUpdateid){
		            	  iMaxUpdateid=iUID;
		              }
		            //    int ilat = (int) (nLat * 1E6);
		            //    int ilng = (int) (nLng * 1E6);
		                if(i==0){
		                    firstLat=ilat;
		                    firstLng=ilng;
		                }
		                GeoPoint mypoint = new GeoPoint(ilat, ilng);
		                
			             String strObjName="POI";
			             try{
			                 strObjName=jObj.getString("comment").toString();
			        
			             }
			             catch(Exception e){
			                 strObjName="POI";
			             }
			             int myuploadid=jObj.getInt("uploadid");
			             String imgpath="http://www.movingobject.org/testfolder/lbademo/phpservice/"+jObj.getString("imagepath");
			             String name=jObj.getString("fbuserfullname");
						 String comment=jObj.getString("comment");
						 String address=jObj.getString("address");
						 String mydate=jObj.getString("uploaddate");
						 String mytitle=jObj.getString("title");
						 int myflag=jObj.getInt("shareflag");
						if(myflag==0){
								name="Someone";
							}
						String contentString="<html Content-Type: text/html; charset=utf-8> <head></head><body><p><b>" +name+"</b>  have discovered: </p>"+
					    "<p>"+comment+"</p>"+
					    "<p><img src='"+imgpath+"' width='96' height='96' /> </p>"+
					  "<p> at address: "+address+"</p>"+
					 "<p> at time: "+mydate+"</p><p> <a href='http://www.movingobject.org/facebook/showpoi.php?pid="+
					 myuploadid+"' target='_blank'>more...</a></p></body></html>";	

			             OverlayItem overlayitem = new OverlayItem(mypoint,mytitle, contentString);
			             updateresultoverlay.addOverlay(overlayitem);
		     
		            }
	            
	            iOutput=iResults;
	            MAXUPDATEID=String.valueOf(iMaxUpdateid);

	            }
	            else{

	                iResults=0;
	                iOutput=0;
	            }
            } 
            catch (Exception e) {
            	e.printStackTrace();
            	iOutput=0;
			}

            if(firstLat!=0&&firstLng!=0){
             GeoPoint pointFirst = new GeoPoint(firstLat,firstLng);
        //   OverlayItem overlayitem3 = new OverlayItem(point3, "Location3", "You are here3");
             mapController.animateTo(pointFirst);
             //resultoverlay.addOverlay(overlayitem3);
             mFindMeFlag=1;
            }
            
            return iOutput;
     }
        /** 
         * Method that calls the update of the number of new feeds from the server since last update 
         * 
         * @return The result number of new feed from the server
         */ 
        private static int RunUpdatesNum(){
            int iOutput=0;
            int iResults=10;
            int firstLat=0;
            int firstLng=0;
           
            double dLat=Double.parseDouble(mStrLat)/1000000;
            double dLng=Double.parseDouble(mStrLng)/1000000;
			
            String murl="http://www.movingobject.org/facebook/updatefeednumbers.php";
            JSONObject mJOB=new JSONObject();   
            try{
            	
                mJOB.put("fbuserid", FBUserid);
                mJOB.put("keywords", mKeywords.trim());
                mJOB.put("fbfriendlist", FBFriendlist);
                mJOB.put("latitude",mStrLat);
                mJOB.put("longitude",mStrLng);
                mJOB.put("lastupdateid",LastUpdateId);
                mJOB.put("setnumber", mSet_Number);
                mJOB.put("setperiod",mSet_Period);
                mJOB.put("settags", mSet_Tag);
               }
               catch (Exception e){
            	   iOutput=0;
               }
             
            
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
            // Limit
            HttpResponse response;
            String mquery=" ";
            int iAmount=0;
            try {
				HttpPost post = new HttpPost(murl);
			    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			    nameValuePairs.add(new BasicNameValuePair("request", mJOB.toString()));
			    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = client.execute(post);

				
				if (response != null) {
				
				//	InputStream instream = response.getEntity().getContent(); // Get the
					HttpEntity entity = response.getEntity();
					String temp = EntityUtils.toString(entity);
					JSONObject jObject = new JSONObject(temp);
	//				JSONObject jObject = new JSONObject(convertStreamToString(instream));
					JSONObject jObject1=jObject.getJSONObject("query");
					mquery=jObject1.getString("content");
					iAmount=jObject1.getInt("resultamount");
		            
				}
	            
	            iOutput=iAmount;
	        } 
            catch (Exception e) {
            	e.printStackTrace();
            	iOutput=0;
			}
       
            return iOutput;
     }
     
        /** 
         * Method that calls the Yahoo local search to get the result 
         * 
         * @return The result, 1-success, 0-failure
         * @deprecated This is not used any more
         */ 
        public int RunYahooSearch(String url){
            int iOutput=0;
            int iResults=10;
            int firstLat=0;
            int firstLng=0;
//          
            if(resultoverlay.size()>0){
                resultoverlay.clearall();
            }
            HttpClient httpclient = getClient();
             
            // Prepare a request object
            HttpGet httpget = new HttpGet(url);
             
            // Execute the request
            HttpResponse response;
             
            try {
            response = httpclient.execute(httpget);
             
            HttpEntity entity = response.getEntity();
             
            if (entity != null) {
             
            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            JSONObject jObject = new JSONObject(convertStreamToString(instream));
            jObject=jObject.getJSONObject("ResultSet");
            JSONArray results = jObject.getJSONArray("Result");
            
            if(results.length()<iResults){
                iResults=results.length();
            }
            for(int i=0;i<iResults;i++){
                JSONObject jObj=results.getJSONObject(i);
                
                
                //JSONObject location = jObj.getJSONObject("geometry").getJSONObject("location");
                
                double nLat = jObj.getDouble("Latitude");
                double nLng = jObj.getDouble("Longitude");

                    
                int ilat = (int) (nLat * 1E6);
                int ilng = (int) (nLng * 1E6);
                if(i==0){
                    firstLat=ilat;
                    firstLng=ilng;
                }
                GeoPoint mypoint = new GeoPoint(ilat, ilng);
                
             String strObjName="POI";
             try{
                 strObjName=jObj.getString("Title").toString();
        
             }
             catch(Exception e){
                 strObjName="POI";
             }
             
             //OverlayItem overlayitem = new OverlayItem(mypoint, "Result ["+Integer.toString(i)+"]", strObjName);
             OverlayItem overlayitem = new OverlayItem(mypoint, "Result ["+Integer.toString(i)+"]", strObjName);
             resultoverlay.addOverlay(overlayitem);
     
            }
            
            iOutput=iResults;
            //instream.close();
            }
            else{

                iResults=0;
                iOutput=1;
            }
            } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            //mapOverlays.add(resultoverlay);
            if(firstLat!=0||firstLng!=0){
             GeoPoint pointFirst = new GeoPoint(firstLat,firstLng);
        //   OverlayItem overlayitem3 = new OverlayItem(point3, "Location3", "You are here3");
             mapController.animateTo(pointFirst);
             mFindMeFlag=1;
             //resultoverlay.addOverlay(overlayitem3);
            }
            
            return iOutput;
        }
        
        /** 
         * Method that converts a stream data into a string 
         * 
         * @param is the input stream data
         * @return The result string
         */ 
        public static String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
             
            String line = null;
            try {
            while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            }
            } catch (IOException e) {
            e.printStackTrace();
            } finally {
            try {
            is.close();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }
            return sb.toString();
            }
       
        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
 

        /** 
         * Method that calls a URI and returns the answer as a JSON object 
         * 
         * @param uri The URI to be called
         * @return The result JSONObject
         */ 
        private JSONObject executeHttpGet(String uri) throws Exception{
            HttpGet req = new HttpGet(uri);
         
            HttpClient client = new DefaultHttpClient();
            HttpResponse resLogin = client.execute(req);
            BufferedReader r = new BufferedReader(
                    new InputStreamReader(resLogin.getEntity()
                            .getContent()));
            StringBuilder sb = new StringBuilder();
            String s = null;
            while ((s = r.readLine()) != null) {
                sb.append(s);
            }
         
            return new JSONObject(sb.toString());
        }
        
        /** 
         * When the back button is pressed in the main screen, the application recognizes this 
         * as an action to close the application. So a dialog will show up and ask. 
         * 
         */
        @Override
        public void onBackPressed() {
    
        	
        	 AlertDialog.Builder builder = new AlertDialog.Builder(GiscoveryMainActivity.this);
             builder.setMessage("Do you really want to quit this Application? ")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                             GiscoveryMainActivity.this.finish();
                             
                             
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                             dialog.cancel();
                        }
                    });
             AlertDialog alert = builder.create();
             alert.show();
        	
        return;
        }
        
        /** 
         * This method is called when the running instance of the application is going to be moved to the Android's garbage can
         * 
         */
        public void onDestroy() {
            super.onDestroy();
        }


        /** 
         * Inner class within the MainActivity for running Asnyc-tasks 
         * 
         * This class is created to execute the Search process in a different thread 
         * 
         * @author XH 
         * @version 2011.1107 
         * @since 0.1 
         */
        private class SearchTask extends AsyncTask<Void, Integer, Void> {
           
        	 private ProgressDialog dialog; // the dialog used to show output to the user
             protected Context applicationContext; // this variable holds the context of the parent activity
             int iExeResult=0; // the number of search result
            
             /** 
              * Method that is called to show the progress of the thread. This method is not 
              * implemented with any code. 
              */  
            protected void onProgressUpdate() {
            }

            /** 
             * Method that is called after the thread has finished. 
             * 
             * @param result This parameter is not used.  
             */  
            protected void onPostExecute(Void result) {
             	 this.dialog.cancel();
                 if(iExeResult>0){
                	 Toast.makeText(applicationContext, String.valueOf(iExeResult)+" results returned", Toast.LENGTH_LONG).show();
                 }
                 else
                 {
                	 Toast.makeText(applicationContext, "No results returned", Toast.LENGTH_LONG).show();
                 }
            }
            /** 
             * Method that is called before the thread starts
             * The prograssDialog will show the progress of the search
             */  
            @Override
            protected void onPreExecute() {
             // TODO Auto-generated method stub
                this.dialog = ProgressDialog.show(applicationContext, "Searching", "In progress ....", true);
          //   myProgress = 0;
            }
            /** 
             * Method that is called to run in the background during the execution of the thread.
             * Here the RunMOSearch method of the parent Activity is called to execute the search.
             */  
			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				iExeResult=GiscoveryMainActivity.RunMOSearch();
				return null;
			}
        }
        
        /** 
         * Inner class within the MainActivity for running Asnyc-tasks 
         * 
         * This class is created to execute the Update process in a different thread 
         * 
         * @author XH 
         * @version 2011.1107 
         * @since 0.1 
         */
        private class UpdateTask extends AsyncTask<Void, Integer, Void> {
            
       	 private ProgressDialog dialog; // the progress dialog that shows the progress of the updates
            protected Context applicationContext; // the context of the parent Activity
            int iExeResult=0; // number of updated posts
            
            /** 
             * Method that is called to show the progress of the thread. This method is not 
             * implemented with any code. 
             */  
           protected void onProgressUpdate() {
           }

           /** 
            * Method that is called after the thread has finished.
            * In this method, a message will show if there is result or nother
            * 
            * @param result This parameter is not used.  
            */ 
           protected void onPostExecute(Void result) {
            	this.dialog.cancel();
                if(iExeResult>0){
               	 Toast.makeText(applicationContext, String.valueOf(iExeResult)+" updates returned", Toast.LENGTH_LONG).show();
               	 getSharedPreferences(MO_PROF,MODE_PRIVATE)
		            .edit()
		            .putString(LASTUPDATEID, MAXUPDATEID)
		            .commit();
                }
                else
                {
               	 Toast.makeText(applicationContext, "No updates returned", Toast.LENGTH_LONG).show();
                }
           }
           /** 
            * Method that is called before the thread starts
            * The prograssDialog will show the progress of the search
            */  
           @Override
           protected void onPreExecute() {
               this.dialog = ProgressDialog.show(applicationContext, "Updating", "In progress ....", true);
           }
           /** 
            * Method that is called to run in the background during the execution of the thread.
            * Here the RunUpdates method of the parent Activity is called to execute the update.
            */ 
			@Override
			protected Void doInBackground(Void... params) {
				iExeResult=GiscoveryMainActivity.RunUpdates();
				return null;
			}
       }
       
        /** 
         * Inner class within the MainActivity for running Asnyc-tasks 
         * 
         * This class is created to execute the Update (the available number of new posts) process in a different thread 
         * 
         * @author XH 
         * @version 2011.1107 
         * @since 0.1 
         */
        private class UpdateNumTask extends AsyncTask<Void, Integer, Void> {
            
               protected Context applicationContext; // the context of the parent Activity
               int iExeResult=0; // number of available new posts
               
               /** 
                * Method that is called to show the progress of the thread. This method is not 
                * implemented with any code. 
                */  
               protected void onProgressUpdate() {
              }
               /** 
                * Method that is called after the thread has finished.
                * In this method, a message will show the number of available new updates if there is at least 1 new update
                * 
                * @param result This parameter is not used.  
                */ 
              protected void onPostExecute(Void result) {
               	 //this.dialog.cancel();
                   if(iExeResult>0){
                  	 Toast.makeText(applicationContext, String.valueOf(iExeResult)+" new updates available", Toast.LENGTH_LONG).show();
                   }
                   FeedCheckedMark=1;
                  
              }
              /** 
               * Method that is called before the thread starts
               * nothing is implemented in this method
               */ 
              @Override
              protected void onPreExecute() {

              }
              /** 
               * Method that is called to run in the background during the execution of the thread.
               * Here the RunUpdatesNum method of the parent Activity is called to execute the update of numbers.
               */ 
   			@Override
   			protected Void doInBackground(Void... params) {
   				// TODO Auto-generated method stub
   				iExeResult=GiscoveryMainActivity.RunUpdatesNum();
   				return null;
   			}
          }
          
}
